import { Injectable } from '@angular/core';
import { IContent2Component } from './IContent2Component';
import { LazyLoadEvent } from 'primeng/api';
import {
    Content2ServiceProxy,
    ContentSyncServiceProxy,
    PagedContentInput,
    PagedContentOfDictionaryOfStringObject,
    SetStatusWithMenuIdInput,
    SwapSortNumberWithMenuIdInput,
    ToAnotherMenuInput,
    ToOtherMenusInput
} from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { MessageService } from 'abp-ng2-module';
import { AppNotifyService } from '@shared/utils/service/app-notify.service';
import { AppLocalizationService } from '@app/shared/common/localization/app-localization.service';
import { DateTimeHelper } from '@shared/helpers/DateTimeHelper';
import { ContentFormService } from '../content/content-form.Service';
import { AppBsModalService } from '@shared/common/appBsModal/app-bs-modal.service';
import { BsModalRef, ModalOptions } from 'ngx-bootstrap/modal';
import { MovingInfoModalComponent } from './list/moving-info-modal.component';
import { SharingInfo2ModalComponent } from './list/sharing-info2-modal.component';
import { SharedInfoModalComponent } from './list/shared-info-modal.component';
import { ISelectedMenu, ISelectedMenuList } from './list/selected-menu-list';

@Injectable()
export class AppContent2Service {

    constructor(
        private _contentFormService: ContentFormService,
        private _contentServiceProxy: Content2ServiceProxy,
        private message: MessageService,
        private notify: AppNotifyService,
        private _appLocalizationService: AppLocalizationService,
        private _modalService: AppBsModalService,
        private _aa: ContentSyncServiceProxy) {

    }


    initListPage(vm: IContent2Component, callBack: { (): void }) {
        this._contentFormService.getConfigAndPermisions(vm, result => {
            vm.pageConfig = result.config;
            vm.customKey = result.config.keyName;
            vm.permissionDic = result.permissions;
                        
            vm.inputPara = Object.assign(new PagedContentInput(),{
                menuId: vm.kind,
                customKey: vm.customKey,
                relateId: vm.relateId,
                infoState: '#',
                filter: '',
                maxResultCount: 10,
                skipCount: 0,
                sorting: vm.pageConfig.diyOrderBy
            });

            if (vm.contentListTab && vm.contentListTab.dataTable) {
                vm.contentListTab.dataTable.reset();
            }

            if (!vm.primengTableHelper.TryChangePage(vm.contentListTab.paginator, 0)) {
                vm.getListData(null);
            }

            if (callBack) {
                callBack();
            }
        });
    }

    //-- action

            
    reloadPage(vm: IContent2Component) {
        if (vm.primengTableHelper.TryChangePage(vm.contentListTab.paginator, vm.contentListTab.paginator.getPage())) {
            return;
        }

        vm.getListData(null);
    }

    getList(
        vm: IContent2Component,
        event?: LazyLoadEvent,
        newGetListFunc?: (body: PagedContentInput | undefined) => Observable<PagedContentOfDictionaryOfStringObject>) {

        vm.contentListTab.selectedDatas = [];
        vm.contentListTab.controller = vm;

        if (vm.primengTableHelper.shouldResetPaging(event)) {
            if (vm.primengTableHelper.TryChangePage(vm.contentListTab.paginator, 0)) {
                return;
            }
        }

        vm.primengTableHelper.showLoadingIndicator();

        let input = vm.inputPara;

        if (vm.contentListTab) {
            input.maxResultCount = vm.primengTableHelper.getMaxResultCount(vm.contentListTab.paginator, event);
            input.skipCount = vm.primengTableHelper.getSkipCount(vm.contentListTab.paginator, event);
        }

        if (newGetListFunc) {
            newGetListFunc(input)
                .pipe(finalize(() => vm.primengTableHelper.hideLoadingIndicator()))
                .subscribe(result => {
                    this.processListData(vm, result);
                });
        } else {
            this._contentServiceProxy.getContentListByPaged(input)
                .pipe(finalize(() => vm.primengTableHelper.hideLoadingIndicator()))
                .subscribe(result => {
                    this.processListData(vm, result);
                });
        }
    }

    swapOrder(vm: IContent2Component) {
        let params =  JSON.parse(JSON.stringify(vm.inputPara));
        params.maxResultCount = 10;
        params.skipCount = 0;

        const pIndex = vm.pageConfig.list.findIndex(t=> (t.fieldName && t.fieldName.toLocaleLowerCase() === 'publishtime'));

        let swapInput = new SwapSortNumberWithMenuIdInput({
            menuId: vm.kind,
            relateId: vm.relateId,
            idOrderList: []
        });
        vm.orderByModal.configure({
            defaultParam: params,
            getDataFunc: (t) => {
                return this._contentServiceProxy.getContentListByPaged(t);
            },
            getTitile: (t) => t.title,
            getTime : (t)=> {
                if(pIndex >= 0){
                    return DateTimeHelper.FromUnixTimestampByMilliseconds(t.publishTime)
                }
                return DateTimeHelper.FromUnixTimestampByMilliseconds(t.creationTime)
            },
            getItemOrder: (t) => t.order,
            getTotolCount: (t) => t.totolCount,
            getItems: (t) => t.items,
            swapOrderFunc: (t) => {
                return this._contentServiceProxy.swapObjectSort(t);
            },
            swapOrderParam: swapInput
        });
        vm.orderByModal.show();
    }

    private processListData(vm: IContent2Component, result: PagedContentOfDictionaryOfStringObject) {
        vm.primengTableHelper.totalRecordsCount = result.totolCount;
        vm.primengTableHelper.records = result.items;
        vm.primengTableHelper.hideLoadingIndicator();
    }

    openCreateOrEdit(vm: IContent2Component, id: string) {
        vm.contentDetailModal.show(id, vm.kind, vm.customKey, vm.relateId, vm.permissionDic, vm.pageConfig);
    }

    deleteItems(vm: IContent2Component) {
        if (vm.contentListTab) {
            let idList = vm.contentListTab.getSelectedIds();

            if (idList.length > 0) {
                this.message.confirm(this._appLocalizationService.l('DeleteWarningMessage'), this._appLocalizationService.l('AreYouSure'),
                    (isConfirmed) => {
                        if (!isConfirmed) return;
                        this._contentServiceProxy.deleteListAysnc(vm.kind, vm.relateId, idList)
                            .subscribe(() => {
                                vm.getListData(null);
                                vm.contentListTab.selectedDatas = [];
                                this.notify.success(this._appLocalizationService.l('SuccessfullyDeleted'));
                            });
                    })
            }
        }
    }

    changeState(vm: IContent2Component, state: boolean) {
        if (vm.contentListTab) {
            let idList = vm.contentListTab.getSelectedIds();

            if (idList.length > 0) {
                let msg: string;
                if (state) {
                    msg = this._appLocalizationService.l('ReleaseWarningMessage');
                }
                else {
                    msg = this._appLocalizationService.l('UndoReleaseWarningMessage');
                }
                this.message.confirm(msg, this._appLocalizationService.l('AreYouSure'),
                    (isConfirmed) => {
                        if (!isConfirmed) return;

                        let input = new SetStatusWithMenuIdInput();
                        input.menuId = vm.kind;
                        input.idList = idList;
                        input.isActive = state;

                        this._contentServiceProxy.setStatus(input)
                            .subscribe(() => {
                                vm.getListData(null);
                                vm.contentListTab.selectedDatas = [];
                                if (state) {
                                    this.notify.success(this._appLocalizationService.l('ReleaseSuccessfully'));
                                } else {
                                    this.notify.success(this._appLocalizationService.l('CancelReleaseSuccessfully'));
                                }
                            });
                    })
            }
        }
    }
    synchorization(vm: IContent2Component) {
        //打开手动同步的窗口页面
    }

    moveToAnotherMenu(vm: IContent2Component, entity: { [key: string]: any; }) {
        const bsModalRef = this._modalService.show(MovingInfoModalComponent, {
            backdrop: 'static', class: 'modal-xl modal-userSelect'
        });
        bsModalRef.content.option = {
            id: entity.id,
            customKey: entity.key,
            kind: vm.kind,
            type: 'MoveToAnotherMenu',
            relateId: vm.relateId,
            selected:[]
        };
        bsModalRef.content.shown();
        bsModalRef.content.callBack = (result : ISelectedMenu) => {
            if (result && result.success) {
                vm.isLoading = true;

                const input = new ToAnotherMenuInput({
                    id: entity.id,
                    menuId: vm.kind,
                    fromMenuId: vm.kind,
                    toMenuId: result.toMenuId,
                    fromRelateId: vm.relateId,
                    toRelateId: result.toRelateId
                });

                this._contentServiceProxy.moveToAnotherMenu(input)
                    .pipe(finalize(() => vm.isLoading = false))
                    .subscribe(result => {
                        this.notify.success(this._appLocalizationService.l('ExecuteSuccessfully'));
                        vm.getListData(null);
                    });
            }
        };
    }

    copyToOtherMenu(vm: IContent2Component, entity: { [key: string]: any; }) {
        const bsModalRef = this._modalService.show(MovingInfoModalComponent, {
            backdrop: 'static', class: 'modal-xl modal-userSelect'
        });
        bsModalRef.content.option = {
            id: entity.id,
            customKey: entity.key,
            kind: vm.kind,
            type: 'Copy',
            relateId: vm.relateId,
            selected:[]
        };
        bsModalRef.content.shown();
        bsModalRef.content.callBack = (result : ISelectedMenu) => {
            if (result && result.success) {
                vm.isLoading = true;

                const input = new ToAnotherMenuInput({
                    id: entity.id,
                    menuId: vm.kind,
                    fromMenuId: vm.kind,
                    toMenuId: result.toMenuId,
                    fromRelateId: vm.relateId,
                    toRelateId: result.toRelateId
                });

                this._contentServiceProxy.copyToOtherMenu(input)
                    .pipe(finalize(() => vm.isLoading = false))
                    .subscribe(result2 => {
                        this.notify.success(this._appLocalizationService.l('ExecuteSuccessfully'));
                        if (result.toMenuId === vm.kind) {
                            vm.getListData(null);
                        }
                    });
            }
        };
    }
    shareToOtherMenu(vm: IContent2Component, entity: { [key: string]: any; }) {
        const bsModalRef = this._modalService.show(SharingInfo2ModalComponent, {
            backdrop: 'static', class: 'modal-xl modal-userSelect'
        });
        bsModalRef.content.option = {
            id: entity.id,
            customKey: entity.key,
            kind: vm.kind,
            type: 'ShareToOtherMenu',
            relateId: vm.relateId,
            selected:[]
        };
        bsModalRef.content.shown();
        bsModalRef.content.callBack = (result : ISelectedMenuList) => {
            if (result && result.success) {
                vm.isLoading = true;

                const input = new ToOtherMenusInput({
                    id: entity.id,
                    menuId: vm.kind,
                    fromMenuId: vm.kind,
                    fromRelateId: vm.relateId,
                    toMenus: result.toMenus,
                    managementType: result.managementType
                });

                this._contentServiceProxy.shareToOtherMenu(input)
                    .pipe(finalize(() => vm.isLoading = false))
                    .subscribe(result2 => {
                        this.notify.success(this._appLocalizationService.l('ExecuteSuccessfully'));
                        vm.getListData(null);
                    });
            }
        };
    }
    lookUpSharedList(vm: IContent2Component, entity: { [key: string]: any; }) {
        const bsModalRef = this._modalService.show(SharedInfoModalComponent, {
            backdrop: 'static', class: 'modal-xl'
        });
        bsModalRef.content.option = {
            id: entity.id,
            customKey: entity.key,
            kind: vm.kind,
            type: '',
            relateId: vm.relateId,
            selected:[]
        };
        bsModalRef.content.shown();
    }

    //-- action end
}
